package com.zhongkai.web.tag;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import com.zhongkai.dao.TagDao;
import com.zhongkai.model.config.Menu;
import com.zhongkai.tools.SpringUtils;

public class ListMenuForLeft extends TagSupport {
	
	Logger log = Logger.getLogger(this.getClass());
	private String menu1="menuList1";
	private String menu2="menuList2";
	private String menu3="menuList3";

	@Override
	public int doEndTag() throws JspException {
		try {
			TagDao tagDao=(TagDao)SpringUtils.getBean("tagDao",this.pageContext.getServletContext());
			List menuList1=new ArrayList();
			List menuList2=new ArrayList();
			List menuList3=new ArrayList();
			StringBuffer hql=new StringBuffer();
			List menuActionList=(List)pageContext.getSession().getAttribute("menuAction");
			if(menuActionList!=null && menuActionList.size()>0){
				hql.append("from Menu where actionKey in (");
				if(menuActionList!=null && menuActionList.size()>0){
					for(int i=0;i<menuActionList.size();i++){
						String actionKey=menuActionList.get(i).toString();
						if(i!=0)
							hql.append(",");
						hql.append("'").append(actionKey).append("'");
					}
				}
				hql.append(")");
				List menuList=tagDao.select(hql.toString());
				if(menuList!=null && menuList.size()>0){
					for(int i=0;i<menuList.size();i++){
						Menu menu=(Menu)menuList.get(i);
						if(menu.getMenuLevel().intValue()==0){
							menuList1.add(menu);
						}
						else if(menu.getMenuLevel().intValue()==1){
							menuList2.add(menu);
						}
						else if(menu.getMenuLevel().intValue()==2){
							menuList3.add(menu);
						}
					}
				}
			}
			pageContext.setAttribute(menu1, menuList1);
			pageContext.setAttribute(menu2, menuList2);
			pageContext.setAttribute(menu3, menuList3);
		} catch (Exception ex) {
			try {
				ex.printStackTrace();
				String path=((HttpServletRequest)pageContext.getRequest()).getContextPath();
				log.error(ex.getMessage());
				((HttpServletResponse) pageContext.getResponse())
						.sendRedirect(path+"/errorpage.jsp?errorinfo="
								+ java.net.URLEncoder.encode(ex.toString(),
										"UTF-8"));
			} catch (java.io.IOException ioe) {
				log.error(ioe.getMessage());
			}
		}
		return EVAL_PAGE;
	}

	public String getMenu1() {
		return menu1;
	}

	public void setMenu1(String menu1) {
		this.menu1 = menu1;
	}

	public String getMenu2() {
		return menu2;
	}

	public void setMenu2(String menu2) {
		this.menu2 = menu2;
	}

	public String getMenu3() {
		return menu3;
	}

	public void setMenu3(String menu3) {
		this.menu3 = menu3;
	}
}
